/**
 * @param {Function} endFnc 父组件通过该函数获取 关联组件绑定的事件数据 endFunc(data)
 * @param {*} data 是绑定的数据
 * @param {*} val  组件事件抛出的值
 */
function endFnc(data, val = {}) {
	data.forEach((item) => {
		const { originId, compId, fn, eventKey } = item;
		// 将要触发的目标组件的 ref实例
		const futureGoalsRef = $store.chart.componentRefs[compId];
		// 将要触发的目标组件的 序号
		const futureGoalsIndex = $store.chart.RenderComponentList.findIndex((item) => item.id === compId);
		const futureGoalsConfig = toRef($store.chart.RenderComponentList[futureGoalsIndex]);
		if (fn === 'customEvent') {
			const fnStr = futureGoalsConfig.value.orgConfig.events.interactHandler[originId]?.[eventKey];
			futureGoalsRef?.customEvent?.(fnStr, futureGoalsRef);
		} else if (fn === 'update') {
			futureGoalsRef?.update?.(val);
		} else {
			futureGoalsRef?.[fn]?.(val);
		}
	});
}

/***
 * @param {Function} callBack 基础事件配置的回调函数，内含参数（所有已渲染组件的ref）
 */
function callBack(fn) {
	fn($store.chart.componentRefs);
}

/**
 *
 * @param {String} originId 当前设置的组件Id
 * @param {Array} componentList 所有渲染的组件数据
 * @param {object} config 当前设置的组件配置
 * @returns
 */
export const useEventHandler = (originId, componentList, config) => {
	const baseEventsPool = {};
	// 交互事件 按事件归类
	const interactEvents = {};

	config.events.interactEvents.forEach((item) => {
		let data = { originId, eventKey: item.interactOn, compId: item.interactComponentId, fn: item.interactFn };
		if (!interactEvents[item.interactOn]) {
			interactEvents[item.interactOn] = [data];
		} else {
			interactEvents[item.interactOn].push(data);
		}
	});

	const { baseEvent } = config.events;
	for (const key in baseEvent) {
		if (Object.hasOwnProperty.call(baseEvent, key)) {
			let fnStr = baseEvent[key] || '';
			let data = interactEvents[key];
			let rest = data ? [endFnc, data] : [];
			if (fnStr || rest.length) {
				baseEventsPool[key] = generateBaseFunc(componentList, fnStr, callBack, ...rest);
			}
		}
	}

	// 子组件抛出的自身事件
	const compSelfEventPool = {};
	const baseEventKeys = Object.keys(baseEvent);
	for (const key in interactEvents) {
		if (baseEventKeys.includes(key)) continue;
		if (Object.hasOwnProperty.call(interactEvents, key)) {
			let data = interactEvents[key];
			compSelfEventPool[key] = (val) => endFnc(data, val);
		}
	}
	return { ...baseEventsPool, ...compSelfEventPool };
};

/**
 * 生成基础函数
 * @param fnStr 用户方法体代码
 * @param event 鼠标事件
 */
export function generateBaseFunc(componentList, fnStr, callBack, ...rest) {
	try {
		let newFun = new Function(`
      return (
        async function(e, componentList, callBack){
          ${fnStr}
        }
      )`)();
		return function (e) {
			if (!fnStr) {
				newFun = null;
			} else {
				newFun(e, componentList, callBack);
			}
			if (rest.length) {
				let [endFnc, data] = rest;
				endFnc(data);
			}
		};
	} catch (error) {
		console.error(error);
	}
}

/**
 * 生成高级函数
 * @param fnStr 用户方法体代码
 * @param e 执行生命周期的动态组件实例
 */
// function generateFunc(fnStr, e) {
// 	try {
// 		// npmPkgs 便于拷贝 echarts 示例时设置option 的formatter等相关内容
// 		Function(`
//       "use strict";
//       return (
//         async function(e, components, node_modules){
//           const {${Object.keys(npmPkgs).join()}} = node_modules;
//           ${fnStr}
//         }
//       )`)().bind(e?.component)(e, components, npmPkgs);
// 	} catch (error) {
// 		console.error(error);
// 	}
// }
